﻿using System;
using System.Linq;
using System.Web.Mvc;
using Mvc3Blog.Infrastructure;
using Mvc3Blog.Models;
using NHibernate;
using NHibernate.Linq;

namespace Mvc3Blog.Controllers
{
    public class PostController : Controller
    {
        public ActionResult Index()
        {
            ISession session = SQLiteUtil.SessionFactory.OpenSession();
            IQueryable<Post> postRepository = session.Query<Post>();
            IQueryable<Post> posts = from d in postRepository
                                     select d;

            return View(posts);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid)
            {
                ISession session = SQLiteUtil.SessionFactory.OpenSession();
                post.CreatedOn = DateTime.Now;
                session.Save(post);
                return RedirectToAction("Index");
            }

            return View(post);
        }

        public ActionResult Edit(int id)
        {
            ISession session = SQLiteUtil.SessionFactory.OpenSession();
            IQueryable<Post> postRepository = session.Query<Post>();
            Post post = postRepository.Single(p => p.Id == id);

            return View(post);
        }

        [HttpPost]
        public ActionResult Edit(Post updatedPost)
        {
            ISession session = SQLiteUtil.SessionFactory.OpenSession();
            IQueryable<Post> postRepository = session.Query<Post>();
            Post oldPost = postRepository.Single(post => post.Id == updatedPost.Id);

            if (ModelState.IsValid)
            {
                oldPost.Title = updatedPost.Title;
                oldPost.Body = updatedPost.Body;
                oldPost.CreatedBy = updatedPost.CreatedBy;
                session.SaveOrUpdate(oldPost);

                return RedirectToAction("Index");
            }
            return View(updatedPost);
        }

        public ActionResult Details(int id)
        {
            ISession session = SQLiteUtil.SessionFactory.OpenSession();
            IQueryable<Post> postRepository = session.Query<Post>();
            Post postDetail = postRepository.Single(post => post.Id == id);
            return View(postDetail);
        }
    }
}